﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Profile;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using Gift.Model;
using Gift.DAL;
using Gift.Model.ENUM;

namespace WebSite.admin.product
{
    public partial class goodsAdd01 : BaseAdmin
    {
        readonly dalCompany theCompany = new dalCompany();
        readonly DALGoods theGoods = new DALGoods();
        readonly DALBrand theBrand = new DALBrand();
        readonly DALTerms theTerms = new DALTerms();
        readonly DALModelType theModelType = new DALModelType();
        readonly DALDeliveryTemplate theDeliveryTemplate = new DALDeliveryTemplate();
        tbGoods oGoods;

       
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.QueryString["gid"] != null)
                {
                    this.btnModelTypeEdit.OnClientClick = Window1.GetShowReference("/admin/product/modelType.aspx?gid=" + Request.QueryString["gid"]);
                }
                else
                {
                    if (Session["goodsCode"] == null)
                    {
                        Session["goodsCode"] = DateTime.Now.Ticks.ToString();
                    }
                    this.btnModelTypeEdit.OnClientClick = Window1.GetShowReference("/admin/product/modelType.aspx");
                }
                this.Display("0", "|--");
                this.BindCompanyList();
                this.BindBrand();
                this.BindDeliveryTemplate();
                this.BindTerms();
                this.BindForm();
               
            }
        }


        void BindCompanyList()
        {
            DataTable dt = theCompany.GetList("").Tables[0];
            this.ddlCompanyList.DataTextField = "name";
            this.ddlCompanyList.DataValueField = "id";
            this.ddlCompanyList.DataSource = dt;
            this.ddlCompanyList.DataBind();
            this.ddlCompanyList.Items.Insert(0, new ExtAspNet.ListItem("请选择...", ""));
        }


        void BindDeliveryTemplate()
        {
            DataTable dt = theDeliveryTemplate.GetList("").Tables[0];
            this.ddlDeliveryTemplate.DataTextField = "TemplateName";
            this.ddlDeliveryTemplate.DataValueField = "id";
            this.ddlDeliveryTemplate.DataSource = dt;
            this.ddlDeliveryTemplate.DataBind();
            this.ddlDeliveryTemplate.Items.Insert(0, new ExtAspNet.ListItem("请选择...", "-1"));
            this.ddlDeliveryTemplate.SelectedValue = this.ddlDeliveryTemplate.Items[0].Value;
        }

        void BindForm()
        {
            if (Request.QueryString["gid"] != null)
            {
                oGoods = theGoods.GetModel(int.Parse(Request.QueryString["gid"]));
                this.txtGoodsName.Text = oGoods.goodsName;
                this.txtGoodsBatchNo.Text = oGoods.goodsCode;
                if (this.ddlGoodsType.Items.FindByValue(oGoods.typeId.ToString()) != null)
                {
                    this.ddlGoodsType.SelectedValue = this.ddlGoodsType.Items.FindByValue(oGoods.typeId.ToString()).Value;
                }
                if (this.ddlGoodsBrand.Items.FindByValue(oGoods.brandId.ToString()) != null)
                {
                    this.ddlGoodsBrand.SelectedValue = this.ddlGoodsBrand.Items.FindByValue(oGoods.brandId.ToString()).Value;
                }
                if (this.ddlTerms.Items.FindByValue(oGoods.termsId.ToString()) != null)
                {
                    this.ddlTerms.SelectedValue = this.ddlTerms.Items.FindByValue(oGoods.termsId.ToString()).Value;
                }
                if (this.ddlDeliveryTemplate.Items.FindByValue(oGoods.DeliveryTemplateId.ToString()) != null)
                {
                    this.ddlDeliveryTemplate.SelectedValue = this.ddlDeliveryTemplate.Items.FindByValue(oGoods.DeliveryTemplateId.ToString()).Value;
                }
                if (this.ddlCompanyList.Items.FindByValue(oGoods.CompanyId.ToString()) != null)
                {
                    this.ddlCompanyList.SelectedValue = this.ddlCompanyList.Items.FindByValue(oGoods.CompanyId.ToString()).Value;
                }
                this.txtOrder.Text = oGoods.goodsOrder.ToString() ;
                this.txtGoodsCount.Text = oGoods.goodsCount.ToString();
                this.txtPoints.Text = oGoods.changePoints.ToString();
                this.lblBigPic.Text = oGoods.bigPic.ToString();
              
                this.fileGoodsPhoto.Required = false;
                this.fileGoodsPhoto.ShowRedStar = false;

                this.isSale.Checked = oGoods.isSale;
                this.cbxAllowAllCard.Checked = oGoods.AllowAllCard;
                this.cbxIsRecom.Checked = oGoods.IsRecom;
                this.txtDetailUrl.Text = oGoods.DetailUrl;
                this.cbxModelType.Checked = oGoods.IsModelType;
                this.txtGoodsPrice.Text = oGoods.goodsPrice.ToString();
                if (oGoods.IsModelType)
                {
                    this.txtPoints.Hidden = true;
                    this.txtPoints.Required = false;
                    this.WriteModelTypeList();
                }

            }

        }

         void UploadBig()
        {
              if (this.fileGoodsPhoto.FileName.Length / 1024 > 300)
            {
                ExtAspNet.Alert.Show("图片大小不能超过300kb！");
            }
              
              else  if (this.fileGoodsPhoto.FileName.Length > 0)
            {

                string fileName = this.fileGoodsPhoto.ShortFileName;
                fileName = fileName.Replace(":", "_").Replace(" ", "_").Replace("\\", "_").Replace("/", "_");
                fileName = DateTime.Now.Ticks.ToString() + "_" + fileName;
                if (this.fileGoodsPhoto.HasFile)
                {
                    this.fileGoodsPhoto.SaveAs(Server.MapPath("~/uploadfile/product/" + fileName));
                }
                this.lblBigPic.Text = fileName;

            }
           
            else
            {
                ExtAspNet.Alert.Show("请选择上传的图片！");
            }
        }

        protected void btnSave01_Click(object sender, EventArgs e)
        {
            if (!this.cbxModelType.Checked)
            {
                if(string.IsNullOrEmpty(this.txtPoints.Text.Trim()))
                {
                    ExtAspNet.Alert.Show("所需福点数没有输入！");
                    return;
                }
            }
            if (Request.QueryString["gid"] != null)
            {
               
                oGoods = theGoods.GetModel(int.Parse(Request.QueryString["gid"]));
                oGoods.goodsName = this.txtGoodsName.Text.Trim();
                oGoods.goodsCode = this.txtGoodsBatchNo.Text.Trim();
                oGoods.typeId = int.Parse(this.ddlGoodsType.SelectedItem.Value);
                if (this.ddlGoodsBrand.SelectedItem.Value != "-1")
                {
                    oGoods.brandId = int.Parse(this.ddlGoodsBrand.SelectedItem.Value);
                }
                if (this.ddlTerms.SelectedItem.Value != "-1")
                {
                    oGoods.termsId = int.Parse(this.ddlTerms.SelectedItem.Value);
                }
                oGoods.goodsOrder = int.Parse(this.txtOrder.Text.Trim());
                oGoods.goodsCount = int.Parse(this.txtGoodsCount.Text);
                if (!this.cbxModelType.Checked)
                {
                    oGoods.changePoints = int.Parse(this.txtPoints.Text);
                }
         
                oGoods.isSale = this.isSale.Checked;
                oGoods.AllowAllCard = this.cbxAllowAllCard.Checked;
                oGoods.IsRecom = this.cbxIsRecom.Checked;
                if (this.fileGoodsPhoto.FileName.Length > 0)
                {
                    this.UploadBig();
                }
         
                oGoods.bigPic = this.lblBigPic.Text;
                oGoods.smallPic = this.lblBigPic.Text;
                oGoods.DetailUrl = this.txtDetailUrl.Text;
                oGoods.IsModelType = this.cbxModelType.Checked;
                oGoods.goodsPrice = decimal.Parse(this.txtGoodsPrice.Text);
                oGoods.DeliveryTemplateId = int.Parse(this.ddlDeliveryTemplate.SelectedItem.Value);
                if (this.ddlCompanyList.SelectedValue != "")
                {
                    oGoods.CompanyId =  int.Parse(this.ddlCompanyList.SelectedItem.Value);
                }
                theGoods.Update(oGoods);
                ExtAspNet.Alert.Show("保存成功！", "", "window.parent.location='goodsAdd.aspx?gid=" + oGoods.goodsId.ToString() + "'");

            }
            else
            {
                if (this.fileGoodsPhoto.FileName.Length <=0)
                {
                    ExtAspNet.Alert.Show("请选择上传的大图！");
                    return;
                }
                //if (this.fileGoodsSmallPhoto.FileName.Length <=0)
                //{
                //    ExtAspNet.Alert.Show("请选择上传的缩列图！");
                //    return;
                //}
                this.UploadBig();
               // this.UploadSmall();
                oGoods = new tbGoods();
                oGoods.goodsName = this.txtGoodsName.Text.Trim();
                oGoods.goodsCode = this.txtGoodsBatchNo.Text.Trim();
                oGoods.typeId = int.Parse(this.ddlGoodsType.SelectedItem.Value);
                if (this.ddlGoodsBrand.SelectedItem.Value != "-1")
                {
                    oGoods.brandId = int.Parse(this.ddlGoodsBrand.SelectedItem.Value);
                }
                if (this.ddlTerms.SelectedItem.Value != "-1")
                {
                    oGoods.termsId = int.Parse(this.ddlTerms.SelectedItem.Value);
                }
                oGoods.goodsOrder = int.Parse(this.txtOrder.Text.Trim());
                oGoods.goodsCount = int.Parse(this.txtGoodsCount.Text);
                if (!this.cbxModelType.Checked)
                {
                    oGoods.changePoints = int.Parse(this.txtPoints.Text);
                }
                oGoods.bigPic = this.lblBigPic.Text;
                oGoods.smallPic = this.lblBigPic.Text;
                oGoods.addAdminId = int.Parse(base.AdminUserId);
                oGoods.addTime = DateTime.Now;
                oGoods.visible = true;
                oGoods.isSale = this.isSale.Checked;
                oGoods.AllowAllCard = this.cbxAllowAllCard.Checked;
                oGoods.DetailUrl = this.txtDetailUrl.Text;
                oGoods.IsModelType = this.cbxModelType.Checked;
                oGoods.goodsPrice = decimal.Parse(this.txtGoodsPrice.Text);
                oGoods.DeliveryTemplateId = int.Parse(this.ddlDeliveryTemplate.SelectedItem.Value);
                if (this.ddlCompanyList.SelectedValue != "")
                {
                    oGoods.CompanyId = int.Parse(this.ddlCompanyList.SelectedItem.Value);
                }
               int pid = theGoods.Add(oGoods);

               if (Session["goodsCode"] != null && this.cbxModelType.Checked)
               {
                   theModelType.Update(Session["goodsCode"].ToString(), pid);
                   Session["goodsCode"] = null;
               }
               ExtAspNet.Alert.Show("保存成功！", "", "window.parent.location='goodsAdd.aspx?gid=" + pid.ToString() + "'");
           //    ExtAspNet.Alert.Show("保存成功！", "", "openNewTab('ProductBrand','product/goodsAdd.aspx?gid=" + pid.ToString() + "','商品列表','AddNewProduct')");

            }
        }

        // void UploadSmall()
        //{
        //    if (this.fileGoodsSmallPhoto.FileName.Length / 1024 > 300)
        //    {
        //        ExtAspNet.Alert.Show("图片大小不能超过300kb！");
        //    }
        //    if (this.fileGoodsSmallPhoto.FileName.Length > 0)
        //    {

        //        string fileName = this.fileGoodsSmallPhoto.ShortFileName;
        //        fileName = fileName.Replace(":", "_").Replace(" ", "_").Replace("\\", "_").Replace("/", "_");
        //        fileName = DateTime.Now.Ticks.ToString() + "_" + fileName;
        //        if (this.fileGoodsSmallPhoto.HasFile)
        //        {
        //            this.fileGoodsSmallPhoto.SaveAs(Server.MapPath("~/uploadfile/product/" + fileName));
        //        }
        //        this.lblSmallPic.Text = fileName;
             
        //    }
        //    else
        //    {
        //        ExtAspNet.Alert.Show("请选择上传的缩列图！");
        //    }
        //}


        private void Display(string parentid, string space)
        {
            string sql = "Select * From tbGoodsType Where parentId =" + parentid + " and isnull(visible,0)=1 Order By typeOrder";
            DataTable table = new DataTable();
            table = SQLAccess.GreatDs(sql).Tables[0];
            if (table.Rows.Count > 0)
            {
                foreach (DataRow row in table.Rows)
                {
                    ExtAspNet.ListItem lt = new ExtAspNet.ListItem(space + "" + row["typeName"].ToString() + "", "" + row["typeId"].ToString() + "");
                    if (row["typedepth"] == null || row["typedepth"].ToString() != "2")
                    {
                        lt.EnableSelect = false;
                    }
                    this.ddlGoodsType.Items.Add(lt);
                    this.Display(row["typeId"].ToString(), "|-" + space);
                }
            }
            if (ddlGoodsType.Items.Count <=0 || ddlGoodsType.Items[0].Value != "-1")
            {
                this.ddlGoodsType.Items.Insert(0, new ExtAspNet.ListItem("请选择...", "-1"));
                this.ddlGoodsType.SelectedValue = this.ddlGoodsType.Items[0].Value;
            }
        }

        void BindBrand()
        {
            DataTable dt = theBrand.GetList("visible = 1").Tables[0];
            this.ddlGoodsBrand.DataTextField = "brandName";
            this.ddlGoodsBrand.DataValueField = "brandId";
            this.ddlGoodsBrand.DataSource = dt;
            this.ddlGoodsBrand.DataBind();
             this.ddlGoodsBrand.Items.Insert(0,new ExtAspNet.ListItem("请选择...","-1"));
            this.ddlGoodsBrand.SelectedValue = this.ddlGoodsBrand.Items[0].Value;
        }


        void BindTerms()
        {
            DataTable dt = theTerms.GetList("").Tables[0];
            this.ddlTerms.DataTextField = "termsName";
            this.ddlTerms.DataValueField = "id";
            this.ddlTerms.DataSource = dt;
            this.ddlTerms.DataBind();
            this.ddlTerms.Items.Insert(0, new ExtAspNet.ListItem("请选择...", "-1"));
            this.ddlTerms.SelectedValue = this.ddlTerms.Items[0].Value;
        }


        protected void Window1_Close(object sender,  ExtAspNet.WindowCloseEventArgs e)
        {
            this.WriteModelTypeList();
        }

        protected void cbxModelType_CheckedChanged(object sender, EventArgs e)
        {
            if (this.cbxModelType.Checked)
            {
                this.txtPoints.Hidden = true;
                this.txtPoints.Required = false;
                this.txtPoints.ShowRedStar = false;
            }
            else
            {
                this.txtPoints.Hidden = false;
                this.txtPoints.Required = true;
            }
        }
        void WriteModelTypeList()
        {
                DataTable tbModelType = null;
                if (Request.QueryString["gid"] != null)
                {
                    tbModelType = theModelType.GetList("goodsId=" + Request.QueryString["gid"] + " and isnull(isDeleted,0) = 0 ").Tables[0];
                }
                else if (Session["goodsCode"] != null)
                {
                    tbModelType = theModelType.GetList("goodsCode=" + Session["goodsCode"].ToString()).Tables[0];
                }
                if (tbModelType != null && tbModelType.Rows.Count > 0)
                {
                    System.Text.StringBuilder sbList = new System.Text.StringBuilder();
                    foreach (DataRow dr in tbModelType.Rows)
                    {
                        sbList.AppendFormat("型号：{0}，福点：{1}，重量：{2}；<br>"
                                              , dr["modelTypeName"].ToString()
                                              , dr["goodsPoints"].ToString()
                                              , dr["goodsWeight"].ToString()
                                              );
                    }
                    this.lblModelTypeList.Text = sbList.ToString();
                }
            
        }
    }
}